package org.popupcommunication.controller;



import javax.validation.Valid;

import org.popupcommunication.model.Group;
import org.popupcommunication.service.GroupManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("admin/group")
public class AdminGroupController {
	
	@Autowired GroupManager groupService;
	private static final String form_ajout ="groups/ajouterGroupe";
	private static final String db_ajout_confirm="groups/confirmationGroupe";
	
	public GroupManager getGroupService() {
		return groupService;
	}
	public void setGroupService(GroupManager groupService) {
		this.groupService = groupService;
	}	

	@InitBinder
	public void initBinder(WebDataBinder binder){
		binder.setAllowedFields(new String[]{
		 "name"	});		
	}
	
	@RequestMapping(value="new",method = RequestMethod.GET)	
	public String showForm (Model model) {		
		model.addAttribute("groupe", new Group());
	return form_ajout;
	}
	
	@RequestMapping(value="",method = RequestMethod.POST)
	public String postForm(
			@ModelAttribute("groupe")  @Valid Group form, BindingResult result) {
		//ajout database
		groupService.registerGroup(form, form.getName(), result);

	return (result.hasErrors() ? form_ajout : db_ajout_confirm);
	}	
}
